<template>
  <div class="headteacher-page">
    <el-card>
      <div class="header-title">班主任管理</div>
      <div class="headteacher-header">
        <el-input v-model="searchName" placeholder="班主任姓名/班主任手机号" class="search-input" clearable />
        <el-select v-model="searchGrade" placeholder="年级" class="search-select" clearable @change="handleGradeChange">
          <el-option v-for="item in gradeOptions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-select v-model="searchClass" placeholder="班级" class="search-select" clearable>
          <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <el-alert :title="`查询结果：共计 ${total} 条数据`" type="info" show-icon class="result-alert" />
      <el-table :data="tableData" border stripe class="headteacher-table">
        <el-table-column prop="headTeacherName" label="班主任姓名" width="180" />
        <el-table-column prop="contactPhone" label="班主任手机号" width="180" />
        <el-table-column prop="className" label="负责班级" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-link type="primary" @click="goEdit(scope.row)">编辑</el-link>
            <el-link type="danger" @click="handleDelete(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="current"
          v-model:page-size="size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getClassList } from '@/api/class';
import { getTeacherById, type TeacherData } from '@/api/teacher';

const router = useRouter();
const tableData = ref<any[]>([]);
const total = ref(0);
const current = ref(1);
const size = ref(10);

const searchName = ref('');
const searchGrade = ref('');
const searchClass = ref('');
const gradeOptions = ref<string[]>([]);
const classOptions = ref<string[]>([]);
let allClassList: any[] = [];

const fetchData = async () => {
  // 1. 获取班级分页数据
  const classRes = await getClassList({ current: current.value, size: size.value });
  const classList = classRes.data.records;
  total.value = classRes.data.total;
  allClassList = classList;

  // 2. 获取所有班主任ID并去重
  const teacherIds = [...new Set(classList.map((item: any) => item.headTeacherId).filter(Boolean))];

  // 3. 批量获取教师信息（无批量接口时循环获取）
  const teacherMap = new Map<number, TeacherData>();
  await Promise.all(
    teacherIds.map(async (id) => {
      const res = await getTeacherById(id);
      teacherMap.set(id, res.data);
    })
  );

  // 4. 合并数据
  tableData.value = classList.map((item: any) => ({
    className: item.className,
    headTeacherName: teacherMap.get(item.headTeacherId)?.name || '',
    contactPhone: teacherMap.get(item.headTeacherId)?.contactPhone || '',
    grade: item.grade,
    classNo: item.classNo,
    headTeacherId: item.headTeacherId,
    id: item.id
  }));

  // 5. 生成年级和班级选项
  gradeOptions.value = [...new Set(classList.map((item: any) => item.grade).filter(Boolean))];
  classOptions.value = [...new Set(classList.map((item: any) => item.className).filter(Boolean))];
};

const handleGradeChange = () => {
  // 选择年级后，班级下拉只显示该年级下的班级
  classOptions.value = [...new Set(allClassList.filter(item => item.grade === searchGrade.value).map(item => item.className))];
  searchClass.value = '';
};

const handleSearch = () => {
  // 重新拉取数据并过滤
  fetchData().then(() => {
    let filtered = tableData.value;
    if (searchName.value) {
      filtered = filtered.filter(item => item.headTeacherName.includes(searchName.value) || item.contactPhone.includes(searchName.value));
    }
    if (searchGrade.value) {
      filtered = filtered.filter(item => item.grade === searchGrade.value);
    }
    if (searchClass.value) {
      filtered = filtered.filter(item => item.className === searchClass.value);
    }
    tableData.value = filtered;
    total.value = filtered.length;
  });
};

const handleReset = () => {
  searchName.value = '';
  searchGrade.value = '';
  searchClass.value = '';
  fetchData();
};

const handleSizeChange = (val: number) => {
  size.value = val;
  fetchData();
};
const handleCurrentChange = (val: number) => {
  current.value = val;
  fetchData();
};

const goAdd = () => {
  router.push('/main/headteacher/add');
};
const goEdit = (row: any) => {
  router.push(`/main/headteacher/edit/${row.id}`);
};
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认删除该班主任吗？', '提示', { type: 'warning' });
    // 这里可以调用删除班主任的接口，或将班级的 headTeacherId 置空
    ElMessage.success('删除成功');
    fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

onMounted(fetchData);
</script>

<style scoped>
.headteacher-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.header-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
}
.headteacher-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.search-input {
  width: 240px;
  margin-right: 8px;
}
.search-select {
  width: 160px;
  margin-right: 8px;
}
.add-btn {
  margin-left: auto;
}
.result-alert {
  margin-bottom: 16px;
}
.headteacher-table {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}
.el-link + .el-link {
  margin-left: 8px;
}
.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style> 